import axios from 'axios'
import store from '../store/index'
import { MessageBox } from 'element-ui'
import api_config from '../../config/api_config'

var schema = api_config.schema
var host = api_config.api_host
var port = api_config.api_port

/* 普通请求 */
let conf = {
  baseURL: `${schema}://${host}:${port}`
}

const axiosCustom = axios.create(conf)

/* 普通请求 */
export const request = (method, url, params = {}, data = {}, config = {}, autoErrorRes = true, autoErrorData = true, autoCancel = true) => {
  if (autoCancel) {
    config = Object.assign({ cancelToken: store.state.source.token }, config)
  }
  const args = Object.assign({
    'method': method,
    'url': url,
    'params': params,
    'data': data
  }, config)

  return axiosCustom(args).then((res) => {
    // 自动处理返回格式错误
    if (autoErrorData && res.data.hasOwnProperty('code') && res.data.code !== "SUCCESS") {
      console.error(res.data)
      const errMsg = res.data.message || '未知的服务器错误，请联系管理员！'
      const errCod = res.data.code
      MessageBox.alert(errMsg, '请求异常：' + errCod, { confirmButtonText: '确定' })
      return Promise.reject(res.data)
    }
    return res.data
  }, (error) => {
    // 自动处理网络请求错误
    console.error(error)
    error.response = error.response || {}
    const errStatus = error.response.status || -100
    if (autoErrorRes && error.message) {
      MessageBox.alert(error.message||'网络请求异常，请联系管理员！', '请求异常：' + errStatus, { confirmButtonText: '确定' })
    }
    return Promise.reject(error)
  })
}

/* 静态资源请求 */
let staticConf = {
  baseURL: "/"
}
// console.log("conf", conf)
const axiosCustomStatic = axios.create(staticConf)
export const requestStatic = (url) => {
  const args = {
    'method': "GET",
    'url': url,
  }

  return axiosCustomStatic(args).then((res) =>{
    return res.data
  }, (error) => {
    console.error(error)
    error.response = error.response || {}
    const errStatus = error.response.status || -100
    if (autoErrorRes && error.message) {
      MessageBox.alert('网络请求异常，请联系管理员！', '请求异常：' + errStatus, { confirmButtonText: '确定' })
    }
    return Promise.reject(error)})
}